<template>
  <el-menu
    ref="domMenu"
    class="el-menu-vertical-demo"
    @select="select"
    background-color="#6c747c"
    text-color="#fff"
    active-text-color="#ffd04b"
  >
    <sub-menu :subMenu="menus"/>
  </el-menu>
</template>

<script lang="ts">
  import { defineComponent, ref, watch, reactive, markRaw } from 'vue'
  // 模块菜单
  import { ElMenu } from 'element-plus'
  import { useRouter } from '@naturefw/ui-core'
  import subMenu from './menu-sub.vue'

  export default defineComponent({
    name: 'nf-ui-elp-menu',
    components: {
      ElMenu,
      subMenu
    },
    props: {
      naviId: { // 导航ID，0：不区分导航
        type: [Number, String],
        default: '0'
      }
    },
    setup(props, context) {

      // 自动展开菜单用
      const domMenu = ref(null)

      const router = useRouter()

      // const menus = reactive([])
      const menus = markRaw([])

      const loadMenu = (id) => {
        menus.length = 0
        if (id) {
          const arr = router.menus.filter((item) => item.naviId == id )
          menus.push(...arr)
        } else {
          menus.push(...router.menus)
        }
      }

      // 导航ID变化后，重新绑定
      watch(() => props.naviId, (id) => {
        loadMenu(id)
      }, {immediate: true})
      
      // 菜单变化后，重新绑定
      watch(router.menus, () => {
        loadMenu(props.naviId)
      })
      
      setTimeout(() => {
        // 打开第一个菜单
        const id = menus[0]?.menuId ?? ''
        if (id) domMenu.value.open(id)
      }, 300)

      // 树叶菜单被选中
      const select = (index, indexPath) => {
        // console.log('select', index, indexPath)
        router.currentRoute.paths = indexPath
        router.currentRoute.key = index
      }

      return {
        domMenu,
        menus,
        select
      }
    }
  })
</script>

<style>
  .el-menu-vertical-demo:not(.el-menu--collapse) {
    max-width: 220px;
    min-height: 400px;
  }
</style>
